<!-- 短剧播放页面 -->
<template>
  <view class="player-page">

    <!-- 顶部导航栏 -->
    <view class="top-navbar">
      <view class="back-button" @click="goBack">
        <image class="back-icon" src="/static/back-icon.png" mode="aspectFit" />
      </view>
      <text class="episode-title">第{{ currentEpisodeId }}集</text>
    </view>

    <!-- 视频播放区域 -->
    <view class="video-container" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd" @click="onVideoClick">
      <!-- 视频播放器 -->
      <video 
        ref="videoPlayer"
        class="video-player"
        :src="currentVideo.url"
        :poster="currentVideo.poster"
        :autoplay="isPlaying"
        :controls="false"
        :show-play-btn="false"
        :show-center-play-btn="false"
        :show-fullscreen-btn="false"
        :show-progress="false"
        :show-loading="false"
        :enable-progress-gesture="false"
        :object-fit="'cover'"
        @play="onVideoPlay"
        @pause="onVideoPause"
        @ended="onVideoEnded"
        @error="onVideoError"
      ></video>

      <!-- 播放控制覆盖层 -->
      <view class="video-overlay">
        <view class="play-button" v-if="!isPlaying">
          <image src="/static/play.png" mode="aspectFit" class="play-icon"></image>
        </view>
      </view>

      <!-- 滑动提示 -->
      <view class="swipe-hint" v-if="touchData.isSwiping && Math.abs(touchData.startY - touchData.moveY) > touchData.swipeThreshold">
        <text class="swipe-text" v-if="touchData.startY - touchData.moveY > touchData.swipeThreshold">向上滑动切换下一集</text>
        <text class="swipe-text" v-else-if="touchData.moveY - touchData.startY > touchData.swipeThreshold">向下滑动切换上一集</text>
      </view>

      <!-- 右侧操作栏 -->
      <view class="action-bar">
        <view class="action-item" @click="toggleFavorite">
          <image :src="dramaInfo.isFavorited ? '/static/star-filled.png' : '/static/short-star.png'" mode="aspectFit" class="action-icon"></image>
          <text class="action-count">{{ dramaInfo.favoriteCount }}</text>
        </view>
        <view class="action-item" @click="showComments">
          <image src="/static/short-comment.png" mode="aspectFit" class="action-icon"></image>
          <text class="action-count">{{ dramaInfo.commentCount }}</text>
        </view>
        <view class="action-item" @click="toggleLike">
          <image :src="dramaInfo.isLiked ? '/static/like-filled.png' : '/static/short-like.png'" mode="aspectFit" class="action-icon"></image>
          <text class="action-count">{{ dramaInfo.likeCount }}</text>
        </view>
      </view>

      <!-- 视频上层信息 -->
      <view class="video-info">
        <text class="drama-title">{{ dramaInfo.title }}</text>
        <text class="drama-description">{{ dramaInfo.description }}</text>
      </view>
    </view>

    <!-- 底部区域 -->
    <view class="bottom-section">
      <!-- 底部操作栏 -->
      <view class="bottom-actions">
        <button class="unified-btn" @click="showEpisodeList">
          <text class="unified-text">选集 全{{ dramaInfo.totalEpisodes }}集 免费观看</text>
          <image src="/static/up.png" mode="aspectFit" class="expand-icon"></image>
        </button>
      </view>
    </view>

    <!-- 选集弹窗 -->
    <view class="episode-modal" v-if="showEpisodeModal" @click="hideEpisodeModal">
      <view class="episode-content" @click.stop>
        <view class="episode-header">
          <text class="episode-modal-title">选集</text>
          <text class="close-btn" @click="hideEpisodeModal">✕</text>
        </view>
        <view class="episode-list">
          <view 
            class="episode-item"
            v-for="(episode, index) in episodeList"
            :key="episode.id"
            :class="{ active: episode.episodeNumber === currentEpisodeId }"
            @click="selectEpisode(episode)"
          >
            <text class="episode-text">第{{ episode.episodeNumber }}集 | {{ episode.title }}</text>
            <text class="episode-status" v-if="!episode.isFree">VIP</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 支付弹窗 -->
    <view class="pay-modal" v-if="showPayModal" @click="hidePayModal">
      <view class="pay-content" @click.stop>
        <view class="pay-header">
          <text class="pay-title">解锁观看</text>
          <text class="close-btn" @click="hidePayModal">✕</text>
        </view>
        <view class="pay-info">
          <text class="pay-desc-text">解锁本剧需支付<text class="pay-amount">¥{{ dramaInfo.unlockPrice || 0 }}</text></text>
        </view>
        <view class="pay-methods-card">
          <view v-if="payState.payStatus === 0" class="pay-methods-loading">
            <text>加载支付方式中...</text>
          </view>
          <view v-else-if="payState.payMethods.length === 0" class="pay-methods-empty">
            <text>暂无可用支付方式</text>
          </view>
          <radio-group v-else @change="onTapPay">
            <label class="pay-method-item" v-for="item in payState.payMethods" :key="item.title">
              <view
                class="pay-item"
                :class="{ 'disabled-pay-item': item.disabled, 'selected': payState.payment === item.value }"
              >
                <view class="pay-item-left">
                  <view class="pay-icon-wrapper">
                    <image
                      class="pay-icon"
                      v-if="item.disabled"
                      :src="sheep.$url.static('/static/img/shop/pay/cod_disabled.png')"
                      mode="aspectFit"
                    />
                    <image
                      class="pay-icon"
                      v-else
                      :src="sheep.$url.static(item.icon)"
                      mode="aspectFit"
                    />
                  </view>
                  <view class="pay-item-info">
                    <text class="pay-method-title" v-if="item.value === 'wallet'">余额支付（¥{{ userBalance.toFixed(2) }}）</text>
                    <text class="pay-method-title" v-else>{{ item.title }}</text>
                    <text class="pay-method-desc" v-if="item.value === 'wallet'">会员钱包,方便取用</text>
                    <text class="pay-method-desc" v-else-if="item.value === 'alipay'">支付宝安全支付</text>
                    <text class="pay-method-desc" v-else-if="item.value === 'wechat'">亿万用户的选择,更快更安全</text>
                    <text class="pay-method-desc" v-else>{{ item.description || '' }}</text>
                  </view>
                </view>
                <view class="pay-item-right">
                  <radio
                    :value="item.value"
                    color="#2977FF"
                    style="transform: scale(0.9)"
                    :disabled="item.disabled"
                    :checked="payState.payment === item.value"
                  />
                </view>
              </view>
            </label>
          </radio-group>
        </view>
        <view class="pay-footer">
          <button v-if="payState.payStatus === 0" class="pay-btn" disabled>
            检测支付环境中
          </button>
          <button v-else-if="payState.payStatus === -1" class="pay-btn" disabled>
            支付已过期
          </button>
          <button
            v-else
            class="pay-btn"
            @click="handlePay"
            :disabled="payState.payStatus === 2 || payState.payStatus === -1"
            :class="{ 'disabled-btn': payState.payStatus === 2 || payState.payStatus === -1 }"
          >
            去解锁
          </button>
        </view>
      </view>
    </view>

    <!-- 评论弹窗 -->
    <view class="comment-modal" v-if="showCommentModal" @click="hideCommentModal">
      <view class="comment-content" @click.stop>
        <view class="comment-header">
          <text class="comment-modal-title">评论 ({{ commentCount }})</text>
          <text class="close-btn" @click="hideCommentModal">✕</text>
        </view>
        <scroll-view class="comment-list-container" scroll-y>
          <view v-if="commentList.length === 0 && !isLoadingComments" class="no-comments">
            <text>暂无评论，快来抢沙发吧~</text>
          </view>
          <!-- 评论列表 -->
          <view v-if="commentList.length > 0" class="comment-list">
            <template v-for="(comment, index) in commentList" :key="comment.id || index">
              <!-- 主评论 -->
              <view class="comment-item">
                <image :src="comment.userAvatar || '/static/default-avatar.png'" class="comment-avatar" mode="aspectFill" @click.stop="goToProfile(comment.userId)"></image>
                <view class="comment-content-wrapper">
                  <view class="comment-header-row">
                    <text class="comment-username">{{ comment.userName || '用户' }}</text>
                    <text class="comment-time">{{ formatTime(comment.commentTime) }}</text>
                  </view>
                  <text v-if="comment.content" class="comment-text">{{ comment.content }}</text>
                  <!-- 评论图片 -->
                  <view v-if="comment.images && getCommentImages(comment.images).length > 0" class="comment-images">
                    <image 
                      v-for="(img, imgIndex) in getCommentImages(comment.images)" 
                      :key="imgIndex"
                      :src="img" 
                      mode="aspectFill"
                      class="comment-image"
                      @click="previewCommentImage(getCommentImages(comment.images), imgIndex)"
                    ></image>
                  </view>
                  <view class="comment-actions">
                    <view class="reply-btn" @click="handleReply(comment)">
                      <text class="reply-btn-text">回复</text>
                    </view>
                    <view v-if="isMyComment(comment)" class="delete-btn" @click="handleDeleteComment(comment)">
                      <text class="delete-btn-text">删除</text>
                    </view>
                  </view>
                </view>
              </view>
              
              <!-- 回复评论列表 -->
              <view v-if="comment.children && comment.children.length > 0" class="reply-list">
                <view v-for="(reply, replyIndex) in comment.children" :key="reply.id || replyIndex" class="comment-item reply-item">
                  <image :src="reply.userAvatar || '/static/default-avatar.png'" class="comment-avatar" mode="aspectFill" @click.stop="goToProfile(reply.userId)"></image>
                  <view class="comment-content-wrapper">
                    <view class="comment-header-row">
                      <text class="comment-username">{{ reply.userName || '用户' }}</text>
                      <text class="comment-time">{{ formatTime(reply.commentTime) }}</text>
                    </view>
                    <!-- 回复关系显示 -->
                    <view v-if="reply.replyToUserName" class="reply-to">
                      <text class="reply-to-text">回复</text>
                      <text class="reply-to-name">@{{ reply.replyToUserName }}</text>
                    </view>
                    <text v-if="reply.content" class="comment-text">{{ reply.content }}</text>
                    <!-- 回复评论图片 -->
                    <view v-if="reply.images && getCommentImages(reply.images).length > 0" class="comment-images">
                      <image 
                        v-for="(img, imgIndex) in getCommentImages(reply.images)" 
                        :key="imgIndex"
                        :src="img" 
                        mode="aspectFill"
                        class="comment-image"
                        @click="previewCommentImage(getCommentImages(reply.images), imgIndex)"
                      ></image>
                    </view>
                    <view class="comment-actions">
                      <view class="reply-btn" @click="handleReply(reply)">
                        <text class="reply-btn-text">回复</text>
                      </view>
                      <view v-if="isMyComment(reply)" class="delete-btn" @click="handleDeleteComment(reply)">
                        <text class="delete-btn-text">删除</text>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </template>
          </view>
        </scroll-view>
        <!-- 评论输入框 -->
        <view class="bottom-input">
          <view v-if="replyingComment" class="reply-hint">
            <text class="reply-hint-text">回复 {{ replyingComment.userName }}：</text>
            <text class="cancel-reply" @click="cancelReply">取消</text>
          </view>
          <!-- 图片预览 -->
          <view v-if="selectedImages.length > 0" class="image-preview-list">
            <view v-for="(img, imgIndex) in selectedImages" :key="imgIndex" class="image-preview-item">
              <image :src="img" mode="aspectFill" class="preview-image"></image>
              <view class="delete-image" @click="removeImage(imgIndex)">
                <text class="delete-icon">×</text>
              </view>
            </view>
          </view>
          <view class="input-row">
            <button @tap="chooseImage" class="image-btn" v-if="selectedImages.length < 9">
              <image src="/static/photo.png" mode="aspectFit" class="image-icon"></image>
            </button>
            <input v-model="newComment" type="text" :placeholder="replyingComment ? `回复${replyingComment.userName}...` : '善语结善缘，恶言伤人心'" class="comment-input"/>
            <button @tap="sendComment" class="send-btn">
              <image src="/static/send-icon.png" mode="aspectFit" class="send-icon"></image>
            </button>       
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import ShortDramaUtil from '@/sheep/api/shortdrama/shortdrama'
import FileApi from '@/sheep/api/infra/file'
import userStore from '@/sheep/store/user'
import sheep from '@/sheep'
import PayOrderApi from '@/sheep/api/pay/order'
import PayChannelApi from '@/sheep/api/pay/channel'
import { getPayMethods, goPayResult } from '@/sheep/platform/pay'
import { fen2yuan, useDurationTime } from '@/sheep/hooks/useGoods'
import UserApi from '@/sheep/api/member/user'

// 响应式数据
const isPlaying = ref(true) // 默认播放
const showEpisodeModal = ref(false)
const showCommentModal = ref(false)
const currentEpisodeId = ref(1)
const videoPlayer = ref(null)

// 评论相关数据
const commentList = ref([])
const newComment = ref('')
const isLoadingComments = ref(false)
const replyingComment = ref(null) // 当前正在回复的评论
const selectedImages = ref([]) // 选中的图片（本地路径）
const uploadingImages = ref([]) // 上传后的图片URL
const commentCount = ref(0)

// 支付相关数据
const showPayModal = ref(false)
const userBalance = ref(0) // 用户余额
const payState = reactive({
  orderInfo: {}, // 支付单信息
  payStatus: 0, // 0=检测支付环境, -2=未查询到支付单信息， -1=支付已过期， 1=待支付，2=订单已支付
  payMethods: [], // 可选的支付方式
  payment: '', // 选中的支付方式
  episodeNumber: null, // 需要解锁的集数
})

// 触摸相关数据
const touchData = reactive({
  startY: 0,
  startX: 0,
  moveY: 0,
  moveX: 0,
  isSwiping: false,
  startTime: 0, // 添加开始时间
  swipeThreshold: 100 // 滑动阈值，类似抖音的交互
})

// 视频信息
const currentVideo = ref({
  url: 'https://example.com/video1.mp4',
  poster: 'https://example.com/poster1.jpg'
})

// 短剧信息
const dramaInfo = reactive({
  title: '破镜重圆',
  description: '第1集 | 炎热的夏天正慢慢赶来,让人热得无法呼吸。太地被那太阳光炙烤着,动物们也热得大汗淋滴。有一天,荷花池里的蚊...',
  totalEpisodes: 300,
  favoriteCount: 55,
  commentCount: 55,
  likeCount: 800,
  isFavorited: false,
  isLiked: false,
  chargeStartEpisode: null, // 从第几集开始收费
  unlockPrice: null // 解锁价格（分）
})

// 剧集列表
const episodeList = ref([])
// 当前短剧ID
const currentDramaId = ref(null)

// 页面加载
onLoad((options) => {
  console.log('播放页面加载参数:', options)
  
  // 兼容两种参数格式：dramaId 和 id
  const dramaId = options.dramaId || options.id
  const episodeId = options.episodeId || options.episode
  
  if (dramaId) {
    currentDramaId.value = dramaId
    loadDramaInfo(dramaId)
  } else {
    uni.showToast({
      title: '缺少短剧ID参数',
      icon: 'none'
    })
  }
  
  if (episodeId) {
    currentEpisodeId.value = parseInt(episodeId)
    console.log('设置当前集数:', currentEpisodeId.value)
  }
})

// 加载短剧信息
const loadDramaInfo = async (dramaId) => {
  try {
    // 先获取短剧基本信息（包括收费信息）
    try {
      const dramaInfoRes = await ShortDramaUtil.getShortDramaInfo(dramaId)
      if (dramaInfoRes && dramaInfoRes.code === 0 && dramaInfoRes.data) {
        const data = dramaInfoRes.data
        dramaInfo.chargeStartEpisode = data.chargeStartEpisode || null
        dramaInfo.unlockPrice = data.unlockPrice || null
      }
    } catch (error) {
      console.log('获取短剧信息失败:', error)
    }
    
    // 调用API获取短剧剧集详情
    const response = await ShortDramaUtil.getShortDramaEpisodes(dramaId)
    
    if (response && response.code === 0 && response.data) {
      const data = response.data
      
      // 数据结构是数组，第一个元素包含短剧基本信息
      const firstEpisode = data[0]
      if (firstEpisode) {
        // 更新短剧基本信息
        dramaInfo.title = firstEpisode.dramaName || '短剧'
        dramaInfo.description = firstEpisode.title || ''
        dramaInfo.totalEpisodes = data.length
        dramaInfo.favoriteCount = firstEpisode.favorites || 0
        dramaInfo.commentCount = firstEpisode.commentsCount || 0
        dramaInfo.likeCount = firstEpisode.likes || 0
        // 如果后端返回了状态，则设置；否则保持默认值 false
        if (firstEpisode.isFavorited !== undefined) {
          dramaInfo.isFavorited = firstEpisode.isFavorited
        } else if (userStore().isLogin) {
          // 如果后端没有返回收藏状态，且用户已登录，则检查收藏状态
          const firstEpisodeId = firstEpisode.id
          if (firstEpisodeId) {
            try {
              const favoriteRes = await ShortDramaUtil.checkFavorite(firstEpisodeId)
              if (favoriteRes && favoriteRes.code === 0 && favoriteRes.data !== undefined) {
                dramaInfo.isFavorited = !!favoriteRes.data
              }
            } catch (error) {
              console.log('检查收藏状态失败:', error)
            }
          }
        }
        if (firstEpisode.isLiked !== undefined) {
          dramaInfo.isLiked = firstEpisode.isLiked
        } else if (userStore().isLogin) {
          // 如果后端没有返回点赞状态，且用户已登录，则检查点赞状态
          const firstEpisodeId = firstEpisode.id
          if (firstEpisodeId) {
            try {
              const likeRes = await ShortDramaUtil.checkLike(firstEpisodeId)
              if (likeRes && likeRes.code === 0 && likeRes.data !== undefined) {
                dramaInfo.isLiked = !!likeRes.data
              }
            } catch (error) {
              console.log('检查点赞状态失败:', error)
            }
          }
        }
      }
    
      
      // 更新剧集列表
      if (Array.isArray(data)) {
        episodeList.value = data.map((episode) => ({
          id: episode.id,
          episodeNumber: episode.episodeNumber,
          title: episode.title || `第${episode.episodeNumber}集`,
          url: episode.videoFile || '',
          poster: episode.poster || '',
          duration: episode.duration || 0,
          isFree: episode.isFree !== false, // 默认免费
          isVip: episode.isVip || false,
          dramaName: episode.dramaName,
          status: episode.status
        }))
        
        console.log('更新后的剧集列表:', episodeList.value)
        
        // 如果有剧集数据，设置当前视频
        if (episodeList.value.length > 0) {
          const currentEpisode = episodeList.value.find(ep => ep.episodeNumber === currentEpisodeId.value) || episodeList.value[0]
          if (currentEpisode) {
            // 检查是否需要支付
            if (checkNeedPay(currentEpisode.episodeNumber)) {
              // 需要支付，显示支付弹框
              showPayModalForEpisode(currentEpisode.episodeNumber)
            } else {
              // 不需要支付，正常播放
            currentVideo.value = {
              url: currentEpisode.url,
              poster: currentEpisode.poster
            }
            currentEpisodeId.value = currentEpisode.episodeNumber
            
            // 确保视频开始播放
            isPlaying.value = true
            }
          }
        }
      } else {
        uni.showToast({
          title: '数据格式错误',
          icon: 'none'
        })
      }
    } else {
      uni.showToast({
        title: response?.msg || '获取数据失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    })
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 视频播放控制
const togglePlayPause = () => {
  console.log('togglePlayPause called, isPlaying:', isPlaying.value)
  
  if (isPlaying.value) {
    // 暂停视频
    isPlaying.value = false
    console.log('暂停视频')
  } else {
    // 播放视频
    isPlaying.value = true
    console.log('播放视频')
  }
}

const onVideoPlay = () => {
  isPlaying.value = true
}

const onVideoPause = () => {
  isPlaying.value = false
}

const onVideoEnded = () => {
  isPlaying.value = false
  
  // 延迟一下再自动播放下一集，给用户一个缓冲时间
  setTimeout(() => {
    playNextEpisode(true) // 传递true表示自动播放
  }, 1000)
}

const onVideoError = (error) => {
  uni.showToast({
    title: '视频播放失败',
    icon: 'none'
  })
}

// 播放上一集
const playPreviousEpisode = () => {
  const currentIndex = episodeList.value.findIndex(ep => ep.episodeNumber === currentEpisodeId.value)
  if (currentIndex > 0) {
    const prevEpisode = episodeList.value[currentIndex - 1]
    // 检查是否需要支付
    if (checkNeedPay(prevEpisode.episodeNumber)) {
      showPayModalForEpisode(prevEpisode.episodeNumber)
      return
    }
    currentEpisodeId.value = prevEpisode.episodeNumber
    selectEpisode(prevEpisode)
    
    // 显示切换提示
    uni.showToast({
      title: `切换到第${currentEpisodeId.value}集`,
      icon: 'none',
      duration: 1500
    })
  } else {
    uni.showToast({
      title: '已经是第一集了',
      icon: 'none',
      duration: 1500
    })
  }
}

// 播放下一集
const playNextEpisode = (isAutoPlay = false) => {
  const currentIndex = episodeList.value.findIndex(ep => ep.episodeNumber === currentEpisodeId.value)
  if (currentIndex < episodeList.value.length - 1) {
    const nextEpisode = episodeList.value[currentIndex + 1]
    // 检查是否需要支付
    if (checkNeedPay(nextEpisode.episodeNumber)) {
      showPayModalForEpisode(nextEpisode.episodeNumber)
      return
    }
    currentEpisodeId.value = nextEpisode.episodeNumber
    selectEpisode(nextEpisode)
    
    // 显示切换提示
    const message = isAutoPlay ? `自动播放第${currentEpisodeId.value}集` : `切换到第${currentEpisodeId.value}集`
    uni.showToast({
      title: message,
      icon: 'none',
      duration: 1500
    })
  } else {
    uni.showToast({
      title: '已经是最后一集了',
      icon: 'none',
      duration: 1500
    })
  }
}

// 右侧操作
// 切换收藏状态
const toggleFavorite = async () => {
  // 检查用户是否登录
  if (!userStore().isLogin) {
    // 跳转到登录页面
    uni.navigateTo({
      url: '/pages/index/login'
    })
    return
  }

  const episodeId = getCurrentEpisodeId()
  if (!episodeId) {
    uni.showToast({
      title: '剧集信息加载中，请稍候',
      icon: 'none'
    })
    return
  }

  try {
    // 根据当前状态调用不同的API
    if (dramaInfo.isFavorited) {
      // 取消收藏
      await ShortDramaUtil.cancelFavorite(episodeId)
      dramaInfo.isFavorited = false
      dramaInfo.favoriteCount = Math.max(0, (dramaInfo.favoriteCount || 1) - 1)
    } else {
      // 添加收藏
      await ShortDramaUtil.createFavorite(episodeId)
      dramaInfo.isFavorited = true
      dramaInfo.favoriteCount = (dramaInfo.favoriteCount || 0) + 1
    }
    
    // 操作成功提示
    uni.showToast({
      title: dramaInfo.isFavorited ? '收藏成功' : '取消收藏成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('收藏操作失败:', error)
    // 恢复原来的状态
  dramaInfo.isFavorited = !dramaInfo.isFavorited
    
    uni.showToast({
      title: dramaInfo.isFavorited ? '收藏失败' : '取消收藏失败',
      icon: 'none'
    })
  }
}

// 获取当前剧集的ID
const getCurrentEpisodeId = () => {
  const currentEpisode = episodeList.value.find(ep => ep.episodeNumber === currentEpisodeId.value)
  return currentEpisode ? currentEpisode.id : null
}

// 显示评论弹窗
const showComments = () => {
  const episodeId = getCurrentEpisodeId()
  if (!episodeId) {
  uni.showToast({
      title: '剧集信息加载中，请稍候',
    icon: 'none'
  })
    return
  }
  showCommentModal.value = true
  loadComments()
}

// 隐藏评论弹窗
const hideCommentModal = () => {
  showCommentModal.value = false
  replyingComment.value = null
  newComment.value = ''
  selectedImages.value = []
  uploadingImages.value = []
}

// 格式化时间（用于评论列表，显示相对时间）
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  
  let time
  if (typeof timestamp === 'number') {
    time = new Date(timestamp)
  } else if (typeof timestamp === 'string' && !isNaN(timestamp)) {
    time = new Date(parseInt(timestamp))
  } else {
    return ''
  }
  
  if (isNaN(time.getTime())) {
    return ''
  }
  
  const now = new Date()
  const diff = now.getTime() - time.getTime()
  
  // 1分钟内：刚刚
  if (diff < 60 * 1000) {
    return '刚刚'
  }
  
  // 1小时内：X分钟前
  if (diff < 60 * 60 * 1000) {
    const minutes = Math.floor(diff / (60 * 1000))
    return `${minutes}分钟前`
  }
  
  // 24小时内：X小时前
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000))
    return `${hours}小时前`
  }
  
  // 7天内：X天前
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = Math.floor(diff / (24 * 60 * 60 * 1000))
    return `${days}天前`
  }
  
  // 超过7天：显示具体日期
  const year = time.getFullYear()
  const month = String(time.getMonth() + 1).padStart(2, '0')
  const day = String(time.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 加载评论列表
const loadComments = async () => {
  const episodeId = getCurrentEpisodeId()
  if (!episodeId) return
  
  isLoadingComments.value = true
  try {
    const res = await ShortDramaUtil.getEpisodeCommentList(episodeId)
    if (res.code === 0 && res.data) {
      // 处理返回的数据，可能是数组或分页对象
      if (Array.isArray(res.data)) {
        commentList.value = res.data
        commentCount.value = res.data.length
      } else if (res.data.list && Array.isArray(res.data.list)) {
        commentList.value = res.data.list
        commentCount.value = res.data.total || res.data.list.length
      } else if (res.data.records && Array.isArray(res.data.records)) {
        commentList.value = res.data.records
        commentCount.value = res.data.total || res.data.records.length
      } else {
        commentList.value = []
        commentCount.value = 0
      }
    } else {
      commentList.value = []
      commentCount.value = 0
    }
  } catch (error) {
    console.error('获取评论列表出错:', error)
    commentList.value = []
    commentCount.value = 0
  } finally {
    isLoadingComments.value = false
  }
}

// 处理回复
const handleReply = (comment) => {
  replyingComment.value = comment
}

// 取消回复
const cancelReply = () => {
  replyingComment.value = null
}

// 选择图片
const chooseImage = () => {
  const remain = 9 - selectedImages.value.length
  if (remain <= 0) {
    uni.showToast({
      title: '最多选择9张图片',
      icon: 'none'
    })
    return
  }
  
  uni.chooseImage({
    count: remain,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      selectedImages.value = [...selectedImages.value, ...res.tempFilePaths]
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
      if (err.errMsg && !err.errMsg.includes('cancel')) {
        uni.showToast({
          title: '选择图片失败',
          icon: 'none'
        })
      }
    }
  })
}

// 删除选中的图片
const removeImage = (index) => {
  selectedImages.value.splice(index, 1)
  uploadingImages.value.splice(index, 1)
}

// 处理评论图片数据（可能是字符串或数组）
const getCommentImages = (images) => {
  if (!images) return []
  if (Array.isArray(images)) {
    return images.filter(img => img)
  }
  if (typeof images === 'string') {
    return images.split(',').filter(img => img.trim())
  }
  return []
}

// 预览评论图片
const previewCommentImage = (images, currentIndex) => {
  if (images && images.length > 0) {
    uni.previewImage({
      urls: images,
      current: currentIndex || 0
    })
  }
}

// 判断是否是当前用户的评论
const isMyComment = (comment) => {
  if (!comment || !comment.userId) return false
  const currentUser = userStore().userInfo
  return currentUser && currentUser.id && currentUser.id === comment.userId
}

// 删除评论
const handleDeleteComment = (comment) => {
  if (!comment || !comment.id) return
  
  uni.showModal({
    title: '提示',
    content: '确定要删除这条评论吗？',
    confirmText: '删除',
    confirmColor: '#ff0000',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await ShortDramaUtil.deleteEpisodeComment({ id: comment.id })
          if (result.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            // 刷新评论列表
            await loadComments()
            // 更新评论数量
            if (dramaInfo.commentCount > 0) {
              dramaInfo.commentCount--
            }
          } else {
            uni.showToast({
              title: result.msg || '删除失败',
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('删除评论失败:', error)
          uni.showToast({
            title: '删除失败，请重试',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 发送评论
const sendComment = async () => {
  if (!newComment.value.trim() && selectedImages.value.length === 0) {
    uni.showToast({
      title: '请输入评论内容或选择图片',
      icon: 'none'
    })
    return
  }
  
  const episodeId = getCurrentEpisodeId()
  if (!episodeId) {
    uni.showToast({
      title: '剧集ID不存在',
      icon: 'none'
    })
    return
  }
  
  try {
    // 如果有图片，先上传图片
    uploadingImages.value = []
    if (selectedImages.value.length > 0) {
      uni.showLoading({
        title: '上传图片中...'
      })
      
      try {
        const uploadTasks = selectedImages.value.map(async (imagePath) => {
          const result = await FileApi.uploadFile(imagePath, 'drama-episode-comment')
          return result?.data || null
        })
        
        const uploaded = await Promise.all(uploadTasks)
        uploadingImages.value = uploaded.filter(url => url !== null)
        
        if (uploadingImages.value.length !== selectedImages.value.length) {
          uni.showToast({
            title: '部分图片上传失败',
            icon: 'none'
          })
        }
      } catch (uploadError) {
        console.error('上传图片失败:', uploadError)
        uni.showToast({
          title: '图片上传失败，请重试',
          icon: 'none'
        })
        uni.hideLoading()
        return
      }
      
      uni.hideLoading()
    }
    
    const params = {
      episodeId: episodeId,
      content: newComment.value.trim() || ''
    }
    
    // 如果有图片，添加图片参数（可能是字符串用逗号分隔，或数组）
    if (uploadingImages.value.length > 0) {
      params.images = uploadingImages.value.join(',')
    }
    
    // 如果是回复评论，添加回复相关参数
    if (replyingComment.value) {
      // 如果被回复的评论本身是回复（有parentId且不为0），则使用其parentId作为新回复的parentId
      // 否则使用被回复评论的id作为parentId
      if (replyingComment.value.parentId && replyingComment.value.parentId !== 0) {
        params.parentId = replyingComment.value.parentId
      } else {
        params.parentId = replyingComment.value.id
      }
      params.replyToUserId = replyingComment.value.userId
    }
    
    const res = await ShortDramaUtil.createEpisodeComment(params)
    
    if (res.code === 0) {
      // 发送成功后清空输入框和图片并刷新评论列表
      newComment.value = ''
      selectedImages.value = []
      uploadingImages.value = []
      replyingComment.value = null
      // 刷新评论列表
      await loadComments()
      // 更新评论数量
      if (dramaInfo.commentCount !== undefined) {
        dramaInfo.commentCount++
      }
    } else {
      uni.showToast({
        title: res.msg || '评论失败，请重试',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('发送评论出错:', error)
    uni.hideLoading()
    uni.showToast({
      title: '评论失败，请重试',
      icon: 'none'
    })
  }
}

// 跳转到个人主页
const goToProfile = (userId) => {
  if (!userId) return
  uni.navigateTo({
    url: `/pages/user/profile?userId=${userId}`
  })
}

// 切换点赞状态
const toggleLike = async () => {
  // 检查用户是否登录
  if (!userStore().isLogin) {
    // 跳转到登录页面
    uni.navigateTo({
      url: '/pages/index/login'
    })
    return
  }

  const episodeId = getCurrentEpisodeId()
  if (!episodeId) {
    uni.showToast({
      title: '剧集信息加载中，请稍候',
      icon: 'none'
    })
    return
  }

  try {
    // 根据当前状态调用不同的API
    if (dramaInfo.isLiked) {
      // 取消点赞
      await ShortDramaUtil.cancelLike(episodeId)
      dramaInfo.isLiked = false
      dramaInfo.likeCount = Math.max(0, (dramaInfo.likeCount || 1) - 1)
    } else {
      // 添加点赞
      await ShortDramaUtil.createLike(episodeId)
      dramaInfo.isLiked = true
      dramaInfo.likeCount = (dramaInfo.likeCount || 0) + 1
    }
    
    // 操作成功提示
    uni.showToast({
      title: dramaInfo.isLiked ? '点赞成功' : '取消点赞成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('点赞操作失败:', error)
    // 恢复原来的状态
  dramaInfo.isLiked = !dramaInfo.isLiked
    
    uni.showToast({
      title: dramaInfo.isLiked ? '点赞失败' : '取消点赞失败',
      icon: 'none'
    })
  }
}

// 选集相关
const showEpisodeList = () => {
  showEpisodeModal.value = true
}

const hideEpisodeModal = () => {
  showEpisodeModal.value = false
}

const selectEpisode = async (episode) => {
  // 检查是否需要支付
  if (checkNeedPay(episode.episodeNumber)) {
    // 需要支付，显示支付弹框
    showPayModalForEpisode(episode.episodeNumber)
    hideEpisodeModal()
    return
  }
  
  // 不需要支付，正常切换
  currentEpisodeId.value = episode.episodeNumber
  currentVideo.value = {
    url: episode.url,
    poster: episode.poster
  }
  
  // 更新短剧描述
  dramaInfo.description = episode.title || `第${episode.episodeNumber}集`
  
  // 切换剧集后自动播放
  isPlaying.value = true
  
  // 如果用户已登录，检查新剧集的收藏和点赞状态
  if (userStore().isLogin && episode.id) {
    try {
      // 检查收藏状态
      const favoriteRes = await ShortDramaUtil.checkFavorite(episode.id)
      if (favoriteRes && favoriteRes.code === 0 && favoriteRes.data !== undefined) {
        dramaInfo.isFavorited = !!favoriteRes.data
      }
    } catch (error) {
      console.log('检查收藏状态失败:', error)
    }
    
    try {
      // 检查点赞状态
      const likeRes = await ShortDramaUtil.checkLike(episode.id)
      if (likeRes && likeRes.code === 0 && likeRes.data !== undefined) {
        dramaInfo.isLiked = !!likeRes.data
      }
    } catch (error) {
      console.log('检查点赞状态失败:', error)
    }
  } else {
    // 如果未登录，重置收藏和点赞状态
    dramaInfo.isFavorited = false
    dramaInfo.isLiked = false
  }
  
  // 如果评论弹窗是打开的，重新加载评论列表
  if (showCommentModal.value) {
    loadComments()
  }
  
  hideEpisodeModal()
}

// 检查是否需要支付
const checkNeedPay = (episodeNumber) => {
  // 如果没有设置收费起始集数，则不需要支付
  if (!dramaInfo.chargeStartEpisode || dramaInfo.chargeStartEpisode <= 0) {
    return false
  }
  // 如果当前集数 >= 收费起始集数，则需要支付
  return episodeNumber >= dramaInfo.chargeStartEpisode
}

// 显示支付弹框
const showPayModalForEpisode = async (episodeNumber) => {
  // 检查是否登录
  if (!userStore().isLogin) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    uni.navigateTo({
      url: '/pages/index/login'
    })
    return
  }
  
  payState.episodeNumber = episodeNumber
  showPayModal.value = true
  
  // 设置支付状态为待支付，让按钮显示渐变色
  payState.payStatus = 1
  
  // 获取用户信息（获取余额）
  await getUserBalance()
  
  // 立即设置支付方式（写死的三种）
  await setPayMethods()
  
  // 创建支付订单
  await createPayOrder(episodeNumber)
}

// 获取用户余额
const getUserBalance = async () => {
  try {
    const res = await UserApi.getUserInfo()
    if (res && res.code === 0 && res.data) {
      userBalance.value = res.data.balance || 0
    }
  } catch (error) {
    console.error('获取用户余额失败:', error)
    userBalance.value = 0
  }
}

// 创建支付订单
const createPayOrder = async (episodeNumber) => {
  try {
    // 不重置支付状态，保持为待支付状态（1），让按钮显示渐变色
    // payState.payStatus = 0
    
    if (!currentDramaId.value) {
      uni.showToast({
        title: '短剧信息错误',
        icon: 'none'
      })
      return
    }
    
    // 调用创建支付订单的接口
    const response = await ShortDramaUtil.createUnlockOrder({
      dramaId: currentDramaId.value,
      episodeNumber: episodeNumber
    })
    
    if (response && response.code === 0 && response.data) {
      const payOrderId = response.data.payOrderId || response.data.id
      if (payOrderId) {
        await setPayOrder(payOrderId)
      } else {
        uni.showToast({
          title: response.msg || '创建支付订单失败',
          icon: 'none'
        })
        payState.payStatus = -2
      }
    } else {
      uni.showToast({
        title: response?.msg || '创建支付订单失败',
        icon: 'none'
      })
      payState.payStatus = -2
    }
  } catch (error) {
    console.error('创建支付订单失败:', error)
    uni.showToast({
      title: '创建支付订单失败',
      icon: 'none'
    })
    payState.payStatus = -2
  }
}

// 设置支付订单信息
const setPayOrder = async (payOrderId) => {
  try {
    const { data, code } = await PayOrderApi.getOrder(payOrderId, true)
    if (code !== 0 || !data) {
      payState.payStatus = -2
      return
    }
    payState.orderInfo = data
    checkPayStatus()
    await setPayMethods()
  } catch (error) {
    console.error('获取支付订单失败:', error)
    payState.payStatus = -2
  }
}

// 检查支付状态
const checkPayStatus = () => {
  if (payState.orderInfo.status === 10 || payState.orderInfo.status === 20) {
    // 支付成功
    payState.payStatus = 2
    // 支付成功后，解锁剧集并播放
    unlockAndPlayEpisode(payState.episodeNumber)
  } else if (payState.orderInfo.status === 30) {
    // 支付关闭
    payState.payStatus = -1
  } else {
    payState.payStatus = 1 // 待支付
  }
}

// 获取支付方式
const setPayMethods = async () => {
  try {
    // 写死三种支付方式：余额支付、微信支付、支付宝支付
    payState.payMethods = [
      {
        icon: '/static/balance-pay.png',
        title: '余额支付',
        value: 'wallet',
        disabled: false,
      },
      {
        icon: '/static/wx-pay.png',
        title: '微信支付',
        value: 'wechat',
        disabled: false,
      },
      {
        icon: '/static/ali-pay.png',
        title: '支付宝支付',
        value: 'alipay',
        disabled: false,
      },
    ]
    
    // 自动选择第一个支付方式（余额支付）
    if (payState.payMethods.length > 0) {
      payState.payment = payState.payMethods[0].value
    }
  } catch (error) {
    console.error('设置支付方式失败:', error)
  }
}

// 执行支付
const handlePay = () => {
  if (payState.payment === '') {
    sheep.$helper.toast('请选择支付方式')
    return
  }
  if (payState.payment === 'wallet') {
    uni.showModal({
      title: '提示',
      content: '确定要支付吗?',
      success: function (res) {
        if (res.confirm) {
          sheep.$platform.pay(payState.payment, 'goods', payState.orderInfo.id)
        }
      },
    })
  } else {
    sheep.$platform.pay(payState.payment, 'goods', payState.orderInfo.id)
  }
}

// 解锁并播放剧集
const unlockAndPlayEpisode = (episodeNumber) => {
  const episode = episodeList.value.find(ep => ep.episodeNumber === episodeNumber)
  if (episode) {
    currentEpisodeId.value = episode.episodeNumber
    currentVideo.value = {
      url: episode.url,
      poster: episode.poster
    }
    dramaInfo.description = episode.title || `第${episode.episodeNumber}集`
    isPlaying.value = true
    showPayModal.value = false
    
    uni.showToast({
      title: '解锁成功',
      icon: 'success'
    })
  }
}

// 切换支付方式
const onTapPay = (e) => {
  payState.payment = e.detail.value
}

// 关闭支付弹框
const hidePayModal = () => {
  showPayModal.value = false
  payState.episodeNumber = null
}

// 支付文案提示
const payDescText = computed(() => {
  if (payState.payStatus === 2) {
    return '该订单已支付'
  }
  if (payState.payStatus === 1 && payState.orderInfo && payState.orderInfo.expireTime) {
    const time = useDurationTime(payState.orderInfo.expireTime)
    if (time.ms <= 0) {
      payState.payStatus = -1
      return ''
    }
    return `剩余支付时间 ${time.h}:${time.m}:${time.s} `
  }
  if (payState.payStatus === -2) {
    return '未查询到支付单信息'
  }
  return ''
})

// 视频点击事件
const onVideoClick = (e) => {
  console.log('onVideoClick - 视频被点击')
  togglePlayPause()
}

// 触摸事件处理
const onTouchStart = (e) => {
  const touch = e.touches[0]
  touchData.startY = touch.clientY
  touchData.startX = touch.clientX
  touchData.isSwiping = false
  touchData.startTime = Date.now() // 记录开始时间
  
  console.log('onTouchStart - 开始触摸')
}

const onTouchMove = (e) => {
  const touch = e.touches[0]
  touchData.moveY = touch.clientY
  touchData.moveX = touch.clientX
  
  const deltaY = touchData.moveY - touchData.startY
  const deltaX = touchData.moveX - touchData.startX
  
  // 判断是否为垂直滑动（类似抖音）
  if (Math.abs(deltaY) > Math.abs(deltaX) && Math.abs(deltaY) > 30) {
    touchData.isSwiping = true
  }
}

const onTouchEnd = (e) => {
  const touchDuration = Date.now() - touchData.startTime
  
  console.log('onTouchEnd - isSwiping:', touchData.isSwiping, 'duration:', touchDuration)
  
  // 如果有滑动，处理滑动逻辑
  if (touchData.isSwiping) {
    const deltaY = touchData.moveY - touchData.startY
    
    // 向上滑动切换到下一集（类似抖音）
    if (deltaY < -touchData.swipeThreshold) {
      playNextEpisode()
    }
    // 向下滑动切换到上一集
    else if (deltaY > touchData.swipeThreshold) {
      playPreviousEpisode()
    }
  }
  
  // 重置触摸数据
  touchData.isSwiping = false
  touchData.startY = 0
  touchData.startX = 0
  touchData.moveY = 0
  touchData.moveX = 0
}

</script>

<style lang="scss" scoped>
.player-page {
  width: 100%;
  height: 100vh;
  background: #000;
  position: relative;
  overflow: hidden;
}

// 顶部导航栏
.top-navbar {
  position: fixed;
  top: 80rpx;
  left: 0;
  right: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background: transparent;
  
  .back-button {
    width: 100rpx;
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .back-icon {
      width: 100rpx;
      height: 100rpx;
      filter: brightness(0) invert(1);
    }
  }
  
  .episode-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #fff;
    margin-left: 10rpx;
  }
}

// 视频容器
.video-container {
  position: relative;
  width: 100%;
  height: calc(100vh - 144rpx); // 减去底部区域高度（同步底部区域增高）
  background: #000;
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

// 播放控制覆盖层
.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.1);
  
  .play-button {
    display: flex;
    align-items: center;
    justify-content: center;
    background: transparent;
    border: none;
    box-shadow: none;
    
    .play-icon {
      width: 100rpx;
      height: 100rpx;
    }
  }
}

// 滑动提示
.swipe-hint {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.7);
  padding: 20rpx 40rpx;
  border-radius: 40rpx;
  z-index: 100;
  
  .swipe-text {
    font-size: 24rpx;
    color: #fff;
    white-space: nowrap;
  }
}

// 右侧操作栏
.action-bar {
  position: absolute;
  right: 30rpx;
  bottom: 200rpx;
  display: flex;
  flex-direction: column;
  gap: 40rpx;
  
  .action-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8rpx;
    
    .action-icon {
      width: 40rpx;
      height: 40rpx;
    }
    
    .action-count {
      font-size: 24rpx;
      color: #fff;
      font-weight: 500;
    }
  }
}

// 视频上层信息
.video-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
  padding: 60rpx 30rpx 40rpx;
  z-index: 10;
  
  .drama-title {
    display: block;
    font-size: 36rpx;
    font-weight: 600;
    color: #fff;
    margin-bottom: 16rpx;
  }
  
  .drama-description {
    display: block;
    font-size: 26rpx;
    color: rgba(255, 255, 255, 0.8);
    line-height: 1.5;
  }
}

// 底部区域
.bottom-section {
  background: #000;
  padding: 32rpx 30rpx;
  
}

// 底部操作栏
.bottom-actions {
  display: flex;
  align-items: center;
  
  
  .unified-btn {
    width: 100%;
    height: 80rpx;
    background: rgba(255, 255, 255, 0.15);
    border-radius: 12rpx;
    padding: 20rpx 24rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .unified-text {
      font-size: 24rpx;
      color: #fff;
      font-weight: 500;
    }
    
    .expand-icon {
      width: 24rpx;
      height: 24rpx;
    }
  }
}

// 选集弹窗
.episode-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  z-index: 2000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  
  .episode-content {
    background: #333;
    border-radius: 20rpx 20rpx 0 0;
    width: 100%;
    max-height: 80vh;
    padding: 40rpx 30rpx;
    
    .episode-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 30rpx;
      
      .episode-modal-title {
        font-size: 28rpx;
        font-weight: normal;
        color: #fff;
      }
      
      .close-btn {
        font-size: 32rpx;
        color: #999;
      }
    }
    
    .episode-list {
      max-height: 60vh;
      overflow-y: auto;
      
      .episode-item {
        background: #444;
        border-radius: 12rpx;
        padding: 20rpx;
        margin-bottom: 16rpx;
        border: 2rpx solid transparent;
        display: flex;
        align-items: center;
        justify-content: space-between;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        &.active {
          background: #fff;
          border-color: #fff;
          
          .episode-text {
            color: #333;
          }
          
          .episode-status {
            color: #ff6b35;
            background: rgba(255, 107, 53, 0.2);
          }
        }
        
        .episode-text {
          font-size: 24rpx;
          color: #ccc;
          line-height: 1.4;
          flex: 1;
        }
        
        .episode-status {
          font-size: 20rpx;
          color: #ff6b35;
          background: rgba(255, 107, 53, 0.2);
          padding: 4rpx 12rpx;
          border-radius: 8rpx;
          margin-left: 20rpx;
        }
      }
    }
  }
}

// 支付弹窗
.pay-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .pay-content {
    background: linear-gradient(0deg, #FFFFFF 44%, #DEE9FF 84%, #ACCAFF 106%);
    border-radius: 24rpx;
    width: 90%;
    max-width: 600rpx;
    max-height: 80vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    
    .pay-header {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 40rpx 30rpx 30rpx;
      
      .pay-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }
      
      .close-btn {
        position: absolute;
        right: 30rpx;
        top: 40rpx;
        font-size: 36rpx;
        color: #999;
        width: 48rpx;
        height: 48rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    
    .pay-info {
      padding: 20rpx 30rpx 40rpx;
      text-align: center;
      
      .pay-desc-text {
        display: block;
        font-size: 32rpx;
        color: #000;
        
        .pay-amount {
          font-size: 32rpx;
          font-weight: 600;
          color: #ff6b00;
          margin-left: 4rpx;
        }
      }
    }
    
    .pay-methods-card {
      background: #fff;
      border-radius: 16rpx;
      margin: 0 30rpx 30rpx;
      padding: 10rpx 0;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
      min-height: 200rpx;
      
      .pay-methods-loading,
      .pay-methods-empty {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 60rpx 30rpx;
        text-align: center;
        
        text {
          font-size: 28rpx;
          color: #999;
        }
      }
      
      .pay-method-item {
        display: block;
        
          .pay-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 20rpx 30rpx;
          border-bottom: 1rpx solid #f0f0f0;
          
          &:last-child {
            border-bottom: none;
          }
          
          &.disabled-pay-item {
            opacity: 0.5;
          }
          
          
          .pay-item-left {
            display: flex;
            align-items: center;
            flex: 1;
            
            .pay-icon-wrapper {
              width: 80rpx;
              height: 80rpx;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              margin-right: 24rpx;
              flex-shrink: 0;
              
              .pay-icon {
                width: 80rpx;
                height: 80rpx;
                border-radius: 50%;
              }
            }
            
            .pay-item-info {
              display: flex;
              flex-direction: column;
              flex: 1;
              
              .pay-method-title {
                font-size: 28rpx;
                font-weight: 500;
                color: #333;
                margin-bottom: 8rpx;
              }
              
              .pay-method-desc {
                font-size: 22rpx;
                color: #999;
                line-height: 1.4;
              }
            }
          }
          
          .pay-item-right {
            display: flex;
            align-items: center;
            flex-shrink: 0;
            
            .userInfo-money {
              font-size: 24rpx;
              color: #999;
              margin-right: 16rpx;
            }
          }
        }
      }
    }
    
    .pay-footer {
      padding: 0 30rpx 40rpx;
      display: flex;
      justify-content: center;
      
      .pay-btn {
        width: 60%;
        height: 80rpx;
        background: linear-gradient(90deg, #B276FF 0%, #74A7FF 100%);
        color: #fff;
        border: none;
        border-radius: 40rpx;
        font-size: 30rpx;
        font-weight: 500;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 4rpx 16rpx rgba(178, 118, 255, 0.3);
        
        &::after {
          border: none;
        }
        
        &.disabled-btn {
          background: #ccc;
          color: #999;
          box-shadow: none;
        }
        
        &:disabled {
          background: #ccc;
          color: #999;
          box-shadow: none;
        }
      }
    }
  }
}

.comment-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  z-index: 2000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  
  .comment-content {
    background: #fff;
    border-radius: 20rpx 20rpx 0 0;
    width: 100%;
    max-height: 85vh;
    display: flex;
    flex-direction: column;
    
    .comment-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 30rpx;
      border-bottom: 1rpx solid #f0f0f0;
      
      .comment-modal-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }
      
      .close-btn {
        font-size: 32rpx;
        color: #999;
      }
    }
    
    .comment-list-container {
      flex: 1;
      overflow-y: auto;
      padding: 20rpx 30rpx;
      padding-bottom: 200rpx; // 为底部输入框留出空间
    }
    
    .no-comments {
      text-align: center;
      color: #999;
      padding: 80rpx 0;
      font-size: 26rpx;
    }
    
    .comment-list {
      .comment-item {
        display: flex;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .comment-avatar {
          width: 60rpx;
          height: 60rpx;
          border-radius: 50%;
          margin-right: 20rpx;
          background-color: #f0f0f0;
          flex-shrink: 0;
        }
        
        .comment-content-wrapper {
          flex: 1;
          min-width: 0;
          
          .comment-header-row {
            display: flex;
            align-items: center;
            margin-bottom: 10rpx;
            width: 100%;
            max-width: 100%;
            overflow: hidden;
            
            .comment-username {
              font-size: 26rpx;
              font-weight: 500;
              color: #333;
              flex-shrink: 0;
            }
            
            .comment-time {
              font-size: 22rpx;
              color: #999;
              flex-shrink: 0;
              margin-left: 10rpx;
              white-space: nowrap;
            }
          }
          
          .reply-to {
            display: flex;
            align-items: center;
            margin-bottom: 8rpx;
            font-size: 24rpx;
            
            .reply-to-text {
              color: #999;
              margin-right: 8rpx;
            }
            
            .reply-to-name {
              color: #576b95;
            }
          }
          
          .comment-text {
            font-size: 28rpx;
            color: #666;
            line-height: 40rpx;
            margin-bottom: 10rpx;
            word-break: break-all;
          }
          
          .comment-images {
            display: flex;
            flex-wrap: wrap;
            gap: 10rpx;
            margin: 10rpx 0;
            
            .comment-image {
              width: 150rpx;
              height: 150rpx;
              border-radius: 8rpx;
              background-color: #f5f5f5;
            }
          }
          
          .comment-actions {
            display: flex;
            align-items: center;
            margin-top: 10rpx;
            
            .reply-btn {
              padding: 8rpx 16rpx;
              
              .reply-btn-text {
                font-size: 24rpx;
                color: #576b95;
              }
            }
            
            .delete-btn {
              padding: 8rpx 16rpx;
              margin-left: 20rpx;
              
              .delete-btn-text {
                font-size: 24rpx;
                color: #ff0000;
              }
            }
          }
        }
      }
      
      .reply-list {
        margin-left: 80rpx;
        margin-top: 10rpx;
        padding-left: 20rpx;
        border-left: 2rpx solid #f0f0f0;
        
        .reply-item {
          padding: 15rpx 0;
          border-bottom: 1rpx solid #f5f5f5;
          
          &:last-child {
            border-bottom: none;
          }
          
          .comment-avatar {
            width: 50rpx;
            height: 50rpx;
          }
        }
      }
    }
    
    .bottom-input {
      position: relative;
      padding: 20rpx 30rpx;
      background-color: #fff;
      border-top: 1rpx solid #eee;
      
      .reply-hint {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10rpx 15rpx;
        background-color: #f5f5f5;
        border-radius: 8rpx;
        margin-bottom: 10rpx;
        
        .reply-hint-text {
          font-size: 24rpx;
          color: #576b95;
          flex: 1;
        }
        
        .cancel-reply {
          font-size: 24rpx;
          color: #999;
          padding: 5rpx 10rpx;
        }
      }
      
      .image-preview-list {
        display: flex;
        flex-wrap: wrap;
        gap: 10rpx;
        margin-bottom: 10rpx;
        padding: 10rpx;
        background-color: #f9f9f9;
        border-radius: 8rpx;
        
        .image-preview-item {
          position: relative;
          width: 150rpx;
          height: 150rpx;
          
          .preview-image {
            width: 100%;
            height: 100%;
            border-radius: 8rpx;
            background-color: #f5f5f5;
          }
          
          .delete-image {
            position: absolute;
            top: -10rpx;
            right: -10rpx;
            width: 40rpx;
            height: 40rpx;
            background-color: rgba(0, 0, 0, 0.6);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            
            .delete-icon {
              color: #fff;
              font-size: 32rpx;
              font-weight: bold;
              line-height: 1;
            }
          }
        }
      }
      
      .input-row {
        display: flex;
        align-items: center;
        width: 100%;
        
        .image-btn {
          width: 80rpx;
          height: 80rpx;
          padding: 0;
          margin-right: 10rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          background: transparent;
          border: none;
          box-shadow: none;
          flex-shrink: 0;
          
          &::after {
            border: none;
          }
          
          .image-icon {
            width: 56rpx;
            height: 56rpx;
          }
        }
        
        .comment-input {
          flex: 1;
          height: 80rpx;
          background-color: #f5f5f5;
          border: 1rpx solid #ddd;
          border-radius: 10rpx;
          padding: 0 30rpx;
          font-size: 28rpx;
        }
        
        .send-btn {
          margin-left: 20rpx;
          width: 80rpx;
          height: 80rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0;
          background: transparent;
          border: none;
          box-shadow: none;
          flex-shrink: 0;
          
          &::after {
            border: none;
          }
          
          .send-icon {
            width: 56rpx;
            height: 56rpx;
          }
        }
      }
    }
  }
}
</style>
